package com.watson.mq;

import android.os.AsyncTask;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.watson.MyApp;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;

/**
 * 功能:MQ发送消息工具类
 */
public class SendMessageTask extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... messages) {
        RabbitMQHelper helper = new RabbitMQHelper();
        ConnectionFactory factory = helper.getConnectionFactory();
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            String exchangeName = "wms_push_exchange";
            String routingKey = SPUtils.get(MyApp.getContext(), "U_Id", "") + "";
            String queueName = "wms_push_queue";

            // 声明交换和停止，并约束他们
            channel.exchangeDeclare(exchangeName, "direct", true);  // durable exchange
            channel.queueDeclare(queueName, true, false, false, null);  // durable queue
            channel.queueBind(queueName, exchangeName, routingKey);

            // 以持久模式发布消息
            String message = messages[0];
            channel.basicPublish(exchangeName, routingKey,
                    new com.rabbitmq.client.AMQP.BasicProperties.Builder()
                            .deliveryMode(2)  // make message persistent
                            .build(),
                    message.getBytes("UTF-8"));
            LogUtils.e("RabbitMQ", " [x] Sent '" + message + "'");
            LogUtils.e("RabbitMQ", "发送的消息是" + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
